﻿using CaptchaGen;
using LuShanTea.Admin.Web.Models;
using LuShanTea.Common;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class AdminLoginController : Controller
    {
        public const string VALIDCODE = "VALIDCODE";

        public const string ADMINID = "ADMINID";

        public IAdminUserService AdminUserService { get; set; }
        // GET: AdminLogin
    
        [HttpGet]
        public ActionResult Index()
        {
            //如果已是登入状态将不再登入
            if (Session[ADMINID] != null)
            {
                //todo:跳转到主页面
                return RedirectToAction("Index","Main");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            string code = (string)TempData[VALIDCODE];
            if (code != model.Code)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "验证码错误" });
            }

            var admin = AdminUserService.GetByPhoneNum(model.PhoneNum);
            if (admin == null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "帐户或密码错误" });
            }
            if (AdminUserService.IsLock(admin.Id))
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "您的账户已被锁定，请在" + (admin.LastLoginErrorTime.AddMinutes(30)-DateTime.Now ).Minutes + "分钟后再试" });
            }
            if (!AdminUserService.CheckLogin(model.PhoneNum, model.PassWord))
            {
                AdminUserService.LockAdminUser(admin.Id);
                return Json(new AjaxResult { Status = "error", ErrorMsg = "帐户或密码错误" });
            }
            Session[ADMINID] = admin.Id;
            AdminUserService.UnLockAdminUser(admin.Id);
            return Json(new AjaxResult { Status = "ok" });
        }


        public ActionResult GetValidCode()
        {
            string res;
            string code = CommonHelper.CreateVerifyCode(out res);
            TempData[VALIDCODE] = res;
            Stream ms = ImageFactory.GenerateImage(code, 40, 120, 12, 2);
            return File(ms, "image/jpeg");
        }
    }
}